<?php
/**
 * User login/logout controller
 * 
 * @author paq
 *
 */
class Controller_Login extends Controller_Action
{

	public function __construct(Controller_Front $frontController)
	{
		parent::__construct('login', $frontController);
	}
	
	/**
	 * Shows login form
	 * 
	 * (non-PHPdoc)
	 * @see libraries/ActionController#indexAction()
	 */
	public function indexAction() 
	{
		Log::info('Login - index');
		 
		if (Manager_User::isLogged()) {
			$this->view()->assign('ok_info', 'You are already logged in');
			return $this->view()->display('ok.tpl');
		}
		
		$this->view()->display('user_login.tpl');
	}
	
	/**
	 * Checks if login data are proper
	 * if so, it logs user in
	 * 
	 * @return void
	 */
	public function checkAction()
	{
		// TODO: sprawdzenie podanych danych, wczytanie ich do $users i zalogowanie
		if (!isset($_POST['login'], $_POST['password'])) {
			$this->view()->assign('fail_info', 'go to login panel first');
			return $this->view()->display('fail.tpl');
		}
		
		$user = Manager_User::get($_POST['login'], $_POST['password']);
		//var_dump($user);
		// FIXME: should check again in db if user exists?
		if (!empty($user) && Manager_User::login($user)) {
			$this->view()->assign('ok_info', 'You are now logged in');
			return $this->view()->display('ok.tpl');
		} else {
			$this->view()->assign('fail_info', 'Wrong login, password or problem with your cookies.');
			return $this->view()->display('fail.tpl');
		}
	}
	
	/**
	 * Logs user out
	 * 
	 * @return void
	 */
	public function logoutAction()
	{
		Log::info('Login - logout');	
		if (Manager_User::logout()) {
			$this->view()->assign('ok_info', 'You were logged out');
			return $this->view()->display('ok.tpl');
		} else {
			$this->view()->assign('fail_info', 'Problem with your cookies or sth');
			return $this->view()->display('fail.tpl');
		}
	}
	
}